package com.heiye.blog.ai.strategy.text.impl;

import com.heiye.blog.ai.enums.TextModelTypeEnum;
import com.heiye.blog.ai.helper.AdvisorHelper;
import com.heiye.blog.ai.model.dto.AIChatRequest;
import com.heiye.blog.ai.model.vo.AIResponse;
import com.heiye.blog.ai.model.vo.AiChatReqVO;
import com.heiye.blog.ai.strategy.text.TextModelStrategy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.ai.deepseek.DeepSeekChatOptions;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;

/**
 * @author: heiye
 * @date: 2025/11/07 下午6:24
 * @version: v1.0.0
 * @description: DeepSeeK 官方 deepseek-chat 模型策略实现类
 */
@Slf4j
@Component
public class DeepSeekChatStrategy implements TextModelStrategy {

    @Resource
    private DeepSeekChatModel deepSeekChatModel;

    @Resource
    private AdvisorHelper advisorHelper;

    /**
     * 获取存储类型枚举
     *
     * @return TextModelTypeEnum
     */
    @Override
    public TextModelTypeEnum getTextModelType() {
        return TextModelTypeEnum.DEEPSEEK_CHAT;
    }

    /**
     * 处理流式响应
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public Flux<AIResponse> handleStreamResponse(AIChatRequest aiChatRequest) {
        // 对参数进行审查
        reviewAndOptimizeRequest(aiChatRequest);

        // 用户消息
        String userMessage = aiChatRequest.getUserMessage();

        // 创建 ChatClientRequestSpec
        ChatClient.ChatClientRequestSpec options = ChatClient.create(deepSeekChatModel)
                .prompt()
                .options(DeepSeekChatOptions.builder()
                        .model(getTextModelType().getType())
                        .temperature(aiChatRequest.getTemperature())
                        .build())
                .user(userMessage);

        // 构建基本的 Advisors
        List<Advisor> advisors = advisorHelper.buildAdvisors(aiChatRequest);

        // 添加 advisors
        options.advisors(advisors);

        return options.stream()
                .content().mapNotNull(text -> AIResponse.builder().v(text).build());
    }

    /**
     * 对参数进行审查
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public void reviewAndOptimizeRequest(AIChatRequest aiChatRequest) {
        // https://api-docs.deepseek.com/zh-cn/quick_start/parameter_settings
        // 默认不开启深度思考
        aiChatRequest.setThinkEnable(false);

//        // 获取模型温度
//        Double temperature = aiChatRequest.getTemperature();
//
//        // 如果没设置温度则设置默认温度
//        if (Objects.isNull(temperature)) {
//            // 设置默认温度，这是 deepseek 官网给出的 Temperature 设置，通用对话设置为 1.3
//            aiChatRequest.setTemperature(1.3);
//        }
    }
}
